﻿using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;

namespace ServiceWeb.Libs {

    public class ApiKeyVerificationChannel : DelegatingHandler {

        public const string KeyHeaderName = "x-siloamservicekey";
        public const string KeyHeaderNameHospitalUnitCode = "x-hospitalunitcode";
        KeyVerifier keyVerifier = new KeyVerifier();

        public ApiKeyVerificationChannel() { } 

        public ApiKeyVerificationChannel(HttpMessageHandler innerChannel)
            : base(innerChannel) {
            ///Todo check key from database
                
        }

        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
            IEnumerable<string> values = null;
            bool IsValidKey = false;

            if (request.Headers.TryGetValues(KeyHeaderName, out values)) {
                var key = values.First();
                IsValidKey = this.keyVerifier.Verify(key);
                ///Todo check key from database
                if (IsValidKey) {
                    return base.SendAsync(request, cancellationToken);
                }

            }

            return System.Threading.Tasks.Task.Factory.StartNew(() => {
                var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                response.Content = new StringContent("ApiKey is required! please supply valid apikey");
                return response;

            });
        }

        
    }
}